//
//  CNM_ExDictionary.swift
//  swiftTXH
//
//  Created by Mac mini on 2022/2/25.
//  Copyright © 2022 Mac mini. All rights reserved.
//

import Foundation
import UIKit


public extension Dictionary {
    /// 遍历出 key  / value  转成数组
    func cnm_toArray<V>(_ lambda: (Key, Value) -> V) -> [V] {
        return self.map(lambda)
    }
    
    ///  JSON 字符串 -> 字典
    static func cnm_jsonToDictionary(json: String) -> Dictionary<String, Any>? {
        if let data = (try? JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8, allowLossyConversion: true)!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? Dictionary<String, Any> {
            return data
        } else {
            return nil
        }
    }
    
    /// 字典 -> JSON 字符串
    func cnm_toJSON() -> String? {
        if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions()) {
            return String(data: jsonData, encoding: String.Encoding.utf8)
        } else {
            return nil
        }
    }
}
